<template>
	<view class="page">
		<!-- 课程信息卡片 -->
		<view class="course-card">
			<view class="card-header-brand">
				荷叶木本 · 课堂邀约
			</view>

			<view class="card-title">
				{{ courseInfo.courseName || '课堂信息加载中…' }}
			</view>

			<view class="card-subtitle">
				发起人：{{ courseInfo.teacherName || '——' }}
			</view>

			<!-- 上下两侧时间 + 中间时长 -->
			<view class="card-time-row">
				<view class="time-block">
					<text class="time-main">{{ courseInfo.startTime || '--:--' }}</text>
					<text class="time-sub">{{ courseInfo.date || '日期待定' }}</text>
				</view>

				<view class="duration-block">
					{{ courseInfo.durationText || '时长待定' }}
				</view>

				<view class="time-block">
					<text class="time-main">{{ courseInfo.endTime || '--:--' }}</text>
					<text class="time-sub">{{ courseInfo.date || '日期待定' }}</text>
				</view>
			</view>

			<!-- 课堂编号：优先显示 classBatch -->
			<view class="card-id-row">
				<text class="id-label">目前参与人数</text>
				<text class="id-value">{{ signedStudents.length || 0 }}</text>
			</view>
		</view>

		<!-- 学生选择 -->
		<view class="student-section">
			<view class="student-label">选择上课小朋友</view>
			<picker mode="selector" :range="students" range-key="displayName" @change="onStudentChange">
				<view class="student-picker">
					{{ selectedStudentName || (students.length ? '请选择' : '暂无可选') }}
				</view>
			</picker>
		</view>

		<!-- 接受邀约按钮 -->
		<view class="btn-box">
			<button class="accept-btn" :disabled="!classId || !selectedStudentId" @click="acceptInvite">
				接受邀约
			</button>
		</view>

		<view class="tip-text">
			请确认课堂信息，并选择参加本课堂的小朋友，<br />
			点击“接受邀约”完成预约。
		</view>
	</view>
</template>

<script>
	import api from '@/api/api.js';

	export default {
		data() {
			return {
				classId: '',

				// 课程信息，刚进入时先为空，等接口返回后填充
				courseInfo: {
					courseName: '',
					teacherName: '',
					date: '',
					startTime: '',
					endTime: '',
					durationText: '',
					classBatch: ''
				},

				students: [],
				selectedStudentId: '',
				selectedStudentName: '',
				 signedStudents: [],
				 participateCount:0,
			};
		},

		// 通过路径 /page/attendanceForm/attendanceByUser?classId=xxx 进入
		onLoad(options) {
			this.classId = options.classId || '';
			this.getStudentList();
			this.getClaseById();
			this.checkInRecordByClassId();
		},

		methods: {
			// 查询家长名下的孩子列表
			getStudentList() {
				api.getStudent({
					isTeacher: false
				}).then(
					res => {
						if (res.code === 200) {
							const list = res.data || [];
							// 拼一个 displayName 方便展示
							this.students = list.map(s => ({
								...s,
								displayName: `${s.studentEnglishName || ''} (${s.studentName || ''})`
							}));

							// 默认选第一个小孩
							if (this.students.length > 0) {
								const first = this.students[0];
								this.selectedStudentId = first.id;
								this.selectedStudentName = first.displayName;
							}
						} else {
							uni.showToast({
								title: res.msg || '获取学生失败',
								icon: 'none'
							});
						}
					},
					() => {
						uni.showToast({
							title: '网络异常',
							icon: 'none'
						});
					}
				);
			},

			// 切换孩子
			onStudentChange(e) {
				const index = e.detail.value;
				const stu = this.students[index];
				this.selectedStudentId = stu.id;
				this.selectedStudentName = stu.displayName;
			},
			checkInRecordByClassId() {
				api.checkInRecordByClassId({
					classId: this.classId
				}).then(res => {
					if (res.code == 200) {
						this.signedStudents = res.data.map(stu => ({
							id: stu.id,
							name: `${stu.studentEnglishName} (${stu.studentName})`
						}));
						console.log(this.signedStudents);
						this.participateCount = this.signedStudents.length;

					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				});
			},
			// 根据课堂 id 查询课堂信息
			getClaseById() {
				if (!this.classId) return;

				api.getClaseById({
					id: this.classId
				}).then(
					res => {
						if (res.code === 200 && res.data) {
							const info = res.data;

							// 从 classTimeBegin / classTimeEnd 里切日期 & 时间，并计算时长
							const timeInfo = this.parseClassTime(
								info.classTimeBegin,
								info.classTimeEnd
							);

							this.courseInfo = {
								courseName: info.classTopic || '未命名课程',
								// 如果后端以后补了 teacherName，就用 teacherName；否则先用 teacherId 占位
								teacherName: info.teacherName || `老师ID：${info.teacherId || '未知'}`,
								date: timeInfo.date,
								startTime: timeInfo.startTime,
								endTime: timeInfo.endTime,
								durationText: timeInfo.durationText,
								classBatch: info.classBatch || ''
							};
						} else {
							uni.showToast({
								title: res.msg || '查询不到课堂信息！',
								icon: 'none'
							});
						}
					},
					() => {
						uni.showToast({
							title: '查询不到课堂信息！',
							icon: 'none'
						});
					}
				);
			},

			// 解析时间 & 计算时长
			parseClassTime(beginStr, endStr) {
				if (!beginStr || !endStr) {
					return {
						date: '',
						startTime: '',
						endTime: '',
						durationText: ''
					};
				}

				// "2025-11-20 19:00:00" -> 日期 & HH:mm
				const [date, beginTimeFull] = beginStr.split(' ');
				const [, endTimeFull] = endStr.split(' ');

				const startTime = (beginTimeFull || '').slice(0, 5); // HH:mm
				const endTime = (endTimeFull || '').slice(0, 5);

				// 计算分钟差（注意兼容 iOS，日期里把 - 换成 /）
				const start = new Date(beginStr.replace(/-/g, '/'));
				const end = new Date(endStr.replace(/-/g, '/'));
				let minutes = Math.round((end - start) / 60000);
				if (isNaN(minutes) || minutes < 0) minutes = 0;

				let durationText = '';
				if (minutes <= 0) {
					durationText = '时长待定';
				} else if (minutes < 60) {
					durationText = `${minutes} 分钟`;
				} else {
					const h = Math.floor(minutes / 60);
					const m = minutes % 60;
					durationText = m ? `${h} 小时 ${m} 分钟` : `${h} 小时`;
				}

				return {
					date,
					startTime,
					endTime,
					durationText
				};
			},

			// 接受邀约（先模拟，不调后台）
			acceptInvite() {
				if (!this.classId) {
					uni.showToast({
						title: '课堂信息异常，请重新打开链接',
						icon: 'none'
					});
					return;
				}
				if (!this.selectedStudentId) {
					uni.showToast({
						title: '请选择上课小孩',
						icon: 'none'
					});
					return;
				}
				api.checkInRecord({
					'classId': this.classId,
					'studentId': this.selectedStudentId,
				}).then(
					res => {
						if (res.code == 200) {
							uni.showToast({
								title: '已接受邀约',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
				
					},
					rej => {}
				);
				// TODO: 这里以后调用后端绑定接口，例如 api.bindClassForStudent(...)
				

				// 需要的话，可以稍后跳转到课堂详情页
				// setTimeout(() => {
				//   uni.redirectTo({ url: `/page/xxx/xxx?classId=${this.classId}` });
				// }, 800);
			}
		}
	};
</script>

<style>
	.page {
		background-color: #f3f4f6;
		box-sizing: border-box;
		padding: 15rpx 15rpx;
		background: linear-gradient(to bottom, #e6f4ea 0%, #fdfaf4 100%);
		min-height: 100vh;
		overflow-x: hidden;
	}

	/* 卡片整体：淡灰底 + 两条斜线 */
	.course-card {
	  position: relative;
	  overflow: hidden; /* 防止斜线溢出圆角 */
	
	  border-radius: 24rpx;
	  padding: 28rpx 24rpx 32rpx;
	  margin-bottom: 30rpx;
	
	  /* 微微带灰，不是死白 */
	  background-color: #f7f8fb;
	
	  /* 轻一点的阴影 */
	  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.04);
	}
	
	/* 右上角一条斜线 */
	.course-card::before {
	  content: '';
	  position: absolute;
	  top: 40rpx;
	  right: -80rpx;
	
	  width: 260rpx;
	  height: 2rpx;
	  border-radius: 2rpx;
	
	  /* 从淡绿到透明的细线 */
	  background: linear-gradient(
	    90deg,
	    rgba(53, 184, 107, 0.25),
	    rgba(53, 184, 107, 0)
	  );
	
	  transform: rotate(14deg);
	}
	
	/* 左下角一条角度不同的斜线 */
	.course-card::after {
	  content: '';
	  position: absolute;
	  bottom: 40rpx;
	  left: -60rpx;
	
	  width: 220rpx;
	  height: 2rpx;
	  border-radius: 2rpx;
	
	  /* 灰度一点的细线 */
	  background: linear-gradient(
	    90deg,
	    rgba(0, 0, 0, 0.1),
	    rgba(0, 0, 0, 0)
	  );
	
	  transform: rotate(-12deg);
	}



	/* 顶部品牌行 */
	.card-header-brand {
		font-size: 24rpx;
		color: #8a8f9c;
		margin-bottom: 12rpx;
	}

	/* 课程名称 */
	.card-title {
		font-size: 32rpx;
		font-weight: 700;
		color: #222;
		margin-bottom: 8rpx;
	}

	/* 老师名称 */
	.card-subtitle {
		font-size: 26rpx;
		color: #555;
		margin-bottom: 24rpx;
	}

	/* 时间行：左开始时间，中间时长，右结束时间 */
	.card-time-row {
		flex-direction: row;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 24rpx;
	}

	.time-block {
		display: flex;
		flex-direction: column;
	}

	.time-main {
		font-size: 32rpx;
		font-weight: 700;
		color: #222;
	}

	.time-sub {
		font-size: 22rpx;
		color: #888;
		margin-top: 4rpx;
	}

	.duration-block {
		padding: 4rpx 18rpx;
		border-radius: 999rpx;
		border-width: 1rpx;
		border-style: solid;
		border-color: #d0d4e0;
		font-size: 22rpx;
		color: #555;
	}

	/* 课堂编号行 */
	.card-id-row {
		border-top-width: 1rpx;
		border-top-style: solid;
		border-top-color: #f0f1f5;
		padding-top: 16rpx;
		margin-top: 4rpx;
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}

	.id-label {
		font-size: 24rpx;
		color: #888;
		margin-right: 12rpx;
	}

	.id-value {
		font-size: 26rpx;
		color: #333;
	}

	/* 学生选择区域 */
	.student-section {
		background-color: #ffffff;
		border-radius: 24rpx;
		padding: 20rpx 24rpx;
		box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.04);
		margin-bottom: 40rpx;
	}

	.student-label {
		font-size: 26rpx;
		color: #333;
		margin-bottom: 12rpx;
	}

	.student-picker {
		height: 70rpx;
		line-height: 70rpx;
		border-radius: 14rpx;
		padding: 0 20rpx;
		background-color: #f7f8fb;
		font-size: 26rpx;
		color: #555;
	}

	/* 按钮 */
	.btn-box {
		margin-top: 20rpx;
		margin-bottom: 16rpx;
	}

	.accept-btn {
		width: 100%;
		height: 84rpx;
		line-height: 84rpx;
		border-radius: 999rpx;
		background-color: #35b86b;
		color: #ffffff;
		font-size: 30rpx;
	}

	.accept-btn[disabled] {
		opacity: 0.5;
	}

	.tip-text {
		text-align: center;
		font-size: 24rpx;
		color: #9094a3;
		line-height: 1.6;
		margin-top: 8rpx;
	}
</style>